package com.cfw.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Locale;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class HttpUtil {

	public static HttpServletRequest getCurrentRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	/**
	 * 접속 클라이언트의 IP 확인
	 * @param request
	 * @return
	 */
	public static String getClientIP(final HttpServletRequest request) {
		// L4를 경유하여 접속하는 경우 설정된 헤더값 참조
		final String nsClientIP = request.getHeader("NS-CLIENT-IP");
		String result = "";
		
		if (StringUtils.isEmpty(nsClientIP)) {
			result = request.getRemoteAddr();
		} else {
			result = nsClientIP;
		}
		
		return result;
	}	
	
	/**
	 * 파라메터로 전달받은 파일의 스트림을 HttpServletResponse에 write
	 * @param fileName
	 * @param response
	 * @return
	 */
	public boolean writeResponseFileStream(String fileName, HttpServletResponse response) {
		boolean success = true;
		FileInputStream fileInputStream = null;
		BufferedInputStream bufferedInputStream = null;
		ServletOutputStream servletOutputStream = null;
		BufferedOutputStream bufferedOutputStream = null;
		
		// jquery-filedownload를 지원하기 위해 쿠키설정
		Cookie cookie = new Cookie("fileDownload", "true");
		cookie.setSecure(false);
		cookie.setMaxAge(-1);
		cookie.setPath("/");
		try {
			final File file = new File(fileName);

			fileInputStream = new FileInputStream(file);
			bufferedInputStream = new BufferedInputStream(fileInputStream);
			
			response.reset();
			/* 전송방식이 'file'일 경우, browser 별 설정도 추가하여야 한다 */
		    response.setHeader("Content-type", "application/octet-stream");
		    response.setHeader("Content-Disposition", "attachment; filename=" + FilenameUtils.getName(fileName));
		    response.setHeader("Content-Length", Long.toString(file.length()) );

		    response.setHeader("Content-Transfer-Encoding", "binary");
		    response.setHeader("Pragma", "no-cache");
		    response.setHeader("Cache-Control", "private");
		    response.setHeader("Expires", "0");

			response.addCookie(cookie);
		    
			byte[] buf = new byte[bufferedInputStream.available() + 1];
			
			servletOutputStream = response.getOutputStream();
			bufferedOutputStream = new BufferedOutputStream(servletOutputStream);
			
			int nReadSize = bufferedInputStream.read(buf);
			while (nReadSize != -1) {
				bufferedOutputStream.write(buf, 0, nReadSize);
				nReadSize = bufferedInputStream.read(buf);				
			}
			
			bufferedOutputStream.flush();
			servletOutputStream.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			success = false;
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
		} finally {
			if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
			if (bufferedInputStream != null) { try { bufferedInputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
			if (bufferedOutputStream != null) { try { bufferedOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
			if (servletOutputStream != null) { try { servletOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
		}			
		
		return success;
	}	
	
	private static final Object[][] GRID_LOCALE_RESOURCE_STRING = new Object[][] {
		{Locale.ENGLISH, "en"},
		{Locale.KOREAN, "kr"},
		{Locale.KOREA, "kr"}
	};
	
	public static String getLocaleString(HttpServletRequest request) {
		for (Object[] def : GRID_LOCALE_RESOURCE_STRING) {
			if (((Locale)def[0]).equals(request.getLocale())) {
				return (String)def[1];
			}
		}
		return null;
	}
}
